package com.bsoft.gol.hcs.satisfaction.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.bsoft.gol.hcs.clinical.bean.qo.DepartmentListQo;
import com.bsoft.gol.hcs.clinical.bean.qo.DoctorListQo;
import com.bsoft.gol.hcs.clinical.bean.vo.DepartmentListVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DoctorInfo;
import com.bsoft.gol.hcs.clinical.bean.vo.DoctorListVo;
import com.bsoft.gol.hcs.clinical.bean.vo.OrganizationVo;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import com.bsoft.gol.hcs.enumcase.*;
import com.bsoft.gol.hcs.followup.bean.request.DeleteFollowUpFormDTO;
import com.bsoft.gol.hcs.followup.bean.request.FollowUpEducationDTO;
import com.bsoft.gol.hcs.followup.bean.request.FollowUpQuestionnaireDTO;
import com.bsoft.gol.hcs.followup.bean.request.SaveFollowUpFormDTO;
import com.bsoft.gol.hcs.followup.bean.response.FollowUpEducationVO;
import com.bsoft.gol.hcs.followup.bean.response.HangUpFollowUpListVO;
import com.bsoft.gol.hcs.his.bean.request.SendMsgRequest;
import com.bsoft.gol.hcs.his.bean.vo.MsgVariable;
import com.bsoft.gol.hcs.his.service.SendMsgService;
import com.bsoft.gol.hcs.satisfaction.bean.request.*;
import com.bsoft.gol.hcs.satisfaction.bean.response.*;
import com.bsoft.gol.hcs.satisfaction.dao.PatientSatisfactionSurveyAnswerDAO;
import com.bsoft.gol.hcs.satisfaction.dao.PatientSatisfactionSurveyDAO;
import com.bsoft.gol.hcs.satisfaction.dao.TeamSurveyRecordDAO;
import com.bsoft.gol.hcs.satisfaction.entity.PatientSatisfactionSurvey;
import com.bsoft.gol.hcs.satisfaction.entity.PatientSatisfactionSurveyAnswer;
import com.bsoft.gol.hcs.satisfaction.entity.TeamSurveyRecord;
import com.bsoft.gol.hcs.specialist.bean.request.FollowUpCancelAllDTO;
import com.bsoft.gol.hcs.specialist.bean.request.FollowUpCancelDTO;
import com.bsoft.gol.hcs.specialist.bean.request.FollowUpFinishDTO;
import com.bsoft.gol.hcs.specialist.bean.request.FollowUpHangUpDTO;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.FusAfterPendingRecord;
import com.bsoft.gol.hcs.specialist.entity.FusHealthEducationEntity;
import com.bsoft.gol.hcs.specialist.entity.SatisfactionHealthEducation;
import com.bsoft.gol.hcs.specialist.entity.SatisfactionRequisitionRecord;
import com.bsoft.gol.hcs.specialist.service.impl.ProduceSatisfactionSurveyPlanServiceImpl;
import com.bsoft.gol.hcs.task.SatisfactionDoctorPushThread;
import com.bsoft.gol.hcs.utils.*;
import com.bsoft.gol.hcs.visitrecord.dao.*;
import com.bsoft.gol.hcs.visitrecord.entity.*;
import com.bsoft.gol.mpi.model.Certificate;
import com.bsoft.gol.mpi.model.Person;
import com.bsoft.gol.mpi.model.Unique;
import com.bsoft.gol.mpi.provider.IMPIProvider;
import com.bsoft.gol.mpi.service.MPIException;
import com.security.cipher.sm.SM4Utils;
import ctd.access.AccessToken;
import ctd.access.loader.AccessTokenLoader;
import ctd.account.AccountCenter;
import ctd.account.UserRoleToken;
import ctd.account.user.User;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.RpcAccess;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.AppContextHolder;
import ctd.util.BeanUtils;
import ctd.util.JSONUtils;
import ctd.util.KeyGenerator;
import ctd.util.annotation.RpcService;
import ctd.util.context.ContextUtils;
import hcn.base.Dept;
import hcn.base.Doctor;
import hcn.base.Organization;
import hcn.base.VrOutpatientVisitRecord;
import hcn.bean.PushMessageBean;
import hcn.bean.UserAllVo;
import hcn.bean.specialist.qo.GroupMemberRequest;
import hcn.bean.specialist.vo.SatisfactionDoctorPushVo;
import hcn.docteam.DocTeamEntity;
import hcn.service.base.IDoctorService;
import hcn.service.base.sendMsg.IMessageSyncService;
import hcn.specialist.DocTeamFusAuthority;
import hcn.util.BaseResponse;
import hcn.util.IdentityTransformUtil;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.atag.core.exception.ServiceException;
import org.atag.util.common.SpringPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import pcn.bean.docTeam.QueryAllDocTeamReq;
import pcn.service.DocIdentityService;
import pcn.service.web.BaseDeviceService;
import pcn.sign.DoctInfo;
import service.rpc.IDocTeamMemberRpcService;
import service.rpc.IDocTeamRpcService;
import service.rpc.IOrganizationRpcService;
import ssdev.bbp.person.IPersonService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.bsoft.gol.hcs.enumcase.VisitRecordEnum.getEnumByKey;

@SsdevService("satisfactionSurveyService")
@Slf4j
public class SatisfactionSurveyService {

    @Autowired
    private ProduceSatisfactionSurveyPlanServiceImpl produceSatisfactionSurveyPlanService;

    @Autowired
    private PatientSatisfactionSurveyDAO patientSatisfactionSurveyDAO;
    @Autowired
    private TeamSurveyRecordDAO teamSurveyRecordDAO;
    @Autowired
    private PatientSatisfactionSurveyAnswerDAO satisfactionSurveyAnswerDAO;
    @Autowired
    private IDocTeamMemberRpcService docTeamMemberRpcService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;
    @Autowired
    private VrApplicationFormDetailDAO vrApplicationFormDetailDAO;
    @Autowired
    private VrApplicationFormRecordDAO vrApplicationFormRecordDAO;
    @Autowired
    private VrDispensingRecordDAO vrDispensingRecordDAO;
    @Autowired
    private VrInpatientVisitRecordDAO vrInpatientVisitRecordDAO;
    @Autowired
    private VrSurgicalRecordDAO vrSurgicalRecordDAO;
    @Autowired
    private VrVisitDiagnosisDAO vrVisitDiagnosisDAO;
    @Resource
    private DocTeamFusAuthorityDAO docTeamFusAuthorityDAO;
    @Autowired
    private SatisfactionHealthEducationDAO satisfactionHealthEducationDAO;
    @Autowired
    private SatisfactionRequisitionRecordDAO satisfactionRequisitionRecordDAO;
    @Autowired
    private FusAfterPendingRecordDAO fusAfterPendingRecordDAO;
    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;
    @Autowired
    private FusHealthEducationDAO fusHealthEducationDAO;
    @SsdevReference("hcn.messageSyncService")
    private IMessageSyncService messageSyncService;
    @SsdevReference("hcn.doctor")
    private IDoctorService doctorService;
    @SsdevReference("hcn.docIdentityService")
    private DocIdentityService docIdentityService;
    @Autowired
    private IOrganizationRpcService organizationRpcService;
    @Autowired
    private IDocTeamRpcService docTeamRpcService;

    @Value("${project_source}")
    private String projectSource;
    @Value("${his_client_url}")
    private String hisUrl;
    @SsdevReference("mpi.mpiProvider")
    private IMPIProvider mpiProvider;
    @Value("satisfaction_survey_dist_url")
    private String satisfactionSurveyDistUrl;


    public static List<DoctorInfo> removeDuplicate(List<DoctorInfo> list) {
        List<DoctorInfo> listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (!listTemp.contains(list.get(i))) {
                listTemp.add(list.get(i));
            }
        }
        return listTemp;
    }

    public static void main(String[] args) {
//        Date d = new Date();
//        LocalDate localDate = LocalDate.now().minusDays(1);
//        String string = localDate.toString();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String dateNowStr = sdf.format(d);
//        System.out.println(dateNowStr);
//        DeptTreeManagerUtils deptTreeManagerUtils = new DeptTreeManagerUtils();
//        TreeNode root = deptTreeManagerUtils.getRoot();
//        TreeNode nodeById = root.findNodeById("寻常疣、扁平疣针灸专病门诊", root);
//        System.out.println(JSONUtils.toString(nodeById.getParentId()));
//        TreeNode nodeById1 = root.findNodeById("慢性咳嗽专病门诊", root);
//        TreeNode nodeById2 = root.findNodeById("男科门诊", root);
//        System.out.println(JSONUtils.toString(nodeById1.getParentId()));
//        System.out.println(JSONUtils.toString(nodeById2.getParentId()));
    }
    @RpcService
    public  void  task(){
        String tenantId = (String) ContextUtils.get("$tenantId");
        if(null == tenantId){
            ContextUtils.put("$tenantId", SpringPropertiesUtil.get("tenantId"));
        }

        log.info("autoProduceSatisfactionSurvey start");
        produceSatisfactionSurveyPlanService.producePlan();
        log.info("autoProduceSatisfactionSurvey end");
    }

    /**
     * 查询满意度调查统计列表
     *
     * @param request
     * @return
     */
    @RpcService
    public SurveyPlanListResponse queryStatisticsList(SurveyPlanListRequest request) {
        log.info("前端的入参打印" + JSONUtils.writeValueAsString(request));
        if (CommonUtils.isNull(request.getDateEnd()) && CommonUtils.isNull(request.getEndDate())) {
            Date d = new Date();
            LocalDate localDate = LocalDate.now().minusDays(1);
            String string = localDate.toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(d);
            request.setBeginDate(dateNowStr);
            request.setEndDate(dateNowStr);
        }
//        if (CommonUtils.isEmpty(request.getNotifyStatus())){
//            request.setNotifyStatus("1");
//        }
        if (CommonUtils.isNull(request.getNotifyStatus())) {
            request.setNotifyStatus("1");
        }
        log.info("接口入参" + JSONUtils.writeValueAsString(request));
        request.setSelectedZxjg("");
        SurveyPlanListResponse response = new SurveyPlanListResponse();

        if (request.getTitleList() != null && request.getTitleList().size() > 0) {
            request.setQueryType(2);
            List<SurveyPlanListResponse.SurveyPlanBean> filterList = patientSatisfactionSurveyDAO.querySatisfactionSurveyPlanList(request);
            List<SurveyPlanListResponse.SurveyPlanBean> responseList = new ArrayList<SurveyPlanListResponse.SurveyPlanBean>();
            if (filterList != null && filterList.size() > 0) {
                for (SurveyPlanListResponse.SurveyPlanBean surveyPlan : filterList) {
                    List<PatientSatisfactionSurveyAnswer> surveyAnswerList =
                            satisfactionSurveyAnswerDAO.querySurveyAnswerBySurveyId(surveyPlan.getPatientSurveyId());
                    if (request.getTitleList() != null && request.getTitleList().size() > 0) {
                        String titleId = "";
                        String answerName = "";
                        String surveyTitleId = "";
                        String surveyAnswerName = "";
                        String filterSign = null;
                        for (int i = 0; i < request.getTitleList().size(); i++) {
                            titleId = request.getTitleList().get(i).getTitleId();
                            answerName = request.getTitleList().get(i).getAnswerName();
                            //题目与题目之间的关系是与，所以每次进入遍历时就把标志设为0，若是上次遍历得到的状态是0，直接退出该循环
                            if (filterSign == null || "1".equals(filterSign)) {
                                filterSign = "0";
                            } else if ("0".equals(filterSign)) {
                                break;
                            }
                            if (surveyAnswerList != null && surveyAnswerList.size() > 0) {
                                for (int j = 0; j < surveyAnswerList.size(); j++) {
                                    surveyTitleId = surveyAnswerList.get(j).getTitleId();
                                    surveyAnswerName = surveyAnswerList.get(j).getAnswerName();

                                    //答案多选的，前端那边按照英文逗号分隔，后台这边拆分逗号，当用户填写的答案包含这些拆分后的答案时，直接把该调查记录返回
                                    if (CommonUtils.isNotEmpty(answerName) && CommonUtils.isNotEmpty(surveyAnswerName)) {
                                        String[] surveyAnswerNameList = answerName.split("\\,");
                                        for (String s : surveyAnswerNameList) {
                                            if (titleId.equals(surveyTitleId) && surveyAnswerName.contains(s)) {
                                                filterSign = "1";
                                            } else {
                                                filterSign = "0";
                                                break;
                                            }
                                        }

                                        if ("1".equals(filterSign)) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        //过滤返回集合重新组合
                        if ("1".equals(filterSign)) {
                            responseList.add(surveyPlan);
                        }
                    }
                }
            }
            if (CommonUtils.isNotEmpty(responseList)) {
                Integer startPage = request.getPageSize() * request.getPageNo() - request.getPageSize() < 0 ? 0 : request.getPageSize() * request.getPageNo() - request.getPageSize();
                Integer size = responseList.size();//记录数
                Integer endPage = request.getPageNo() * request.getPageSize() > size ? size : request.getPageNo() * request.getPageSize();
                if (startPage.intValue() > size) {
                    response.setTotal(0L);
                } else {
                    List<SurveyPlanListResponse.SurveyPlanBean> pageList = responseList.subList(startPage, endPage);
                    response.setList(pageList);
                    response.setTotal(responseList.size());
                }
            }
        } else {
            request.setQueryType(1);
            log.info("request--------------->>" + request);
            List<SurveyPlanListResponse.SurveyPlanBean> list = patientSatisfactionSurveyDAO.querySatisfactionSurveyPlanList(request);
            log.info("请求-----------" + request);
            BigInteger total = patientSatisfactionSurveyDAO.getSatisfactionSurveyPlanCount(request);
            log.info("总长度------------------" + total);
            response.setList(list);
            response.setTotal(total.longValue());
        }
        return response;

    }


    /**
     * 满意度工作统计列表
     *
     * @param request
     * @return
     */
    @RpcService(timeout = 60)
    public List<SurveyPlanWorkListResponseNew> queryStatisticsWorkListNew(QuerySurveyDeptListRequest request) throws ControllerException {
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        if (CommonUtils.isEmpty(request.getQuestionnaireId())) {
            return new ArrayList<>();
        }
        QueryDeptTotalResponse queryDeptTotalResponse = patientSatisfactionSurveyDAO.queryDeptTotal(request);
        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())) {

            queryDeptTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDeptTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }
        log.info("==========================科室评价统计" + JSONUtils.writeValueAsString(queryDeptTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.querySurveyDeptByDeptIdNew(request);

        log.info("查询输出打印=======================================》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponses));
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            log.info("id=======>" + surveyPlanDeptListResponse.getDepartmentId());
            log.info("枚举后的id====" + DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("id"));
            log.info("枚举科室的名称====" + DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("name"));
            response.setDepartmentId(DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("id"));
            response.setDepartmentName(DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("name"));
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            log.info("科室======》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponse.getC()));
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }

            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            BigDecimal d = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getD())) {
                d = new BigDecimal(new Double(0) * 100);

            } else {
                d = new BigDecimal(surveyPlanDeptListResponse.getD() * 100);
            }

            BigDecimal dmum = d.setScale(2, RoundingMode.HALF_UP);
            response.setD(String.valueOf(dmum));


            BigDecimal e = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getE())) {
                e = new BigDecimal(new Double(0) * 100);

            } else {
                e = new BigDecimal(surveyPlanDeptListResponse.getE() * 100);
            }

            BigDecimal Emum = e.setScale(2, RoundingMode.HALF_UP);
            response.setE(String.valueOf(Emum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDepartmentId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDeptId(surveyPlanDeptListResponse.getDepartmentId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                // List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDeptId(req);
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            response.setQueryDeptTotalResponse(queryDeptTotalResponse);
            log.info("前端相应输出=====》" + JSONUtils.writeValueAsString(response));
            planWorkListResponses.add(response);

        }

        List<SurveyPlanWorkListResponseNew> returnResponse = new ArrayList<>();

        Map<String, List<SurveyPlanWorkListResponse>> map = new HashMap<>();

        for (SurveyPlanWorkListResponse response : planWorkListResponses) {
            try {
                String deptId = response.getDepartmentId();
                if (CommonUtils.isNotEmpty(deptId)) {
                    Dept dept = (Dept) Client.rpcInvoke("hcn.department", "getDeptByLocalDeptId", "61caaf61f5b2ba00a46fe46c", deptId);
                    log.info("DeptInfo=====》" + JSONUtils.writeValueAsString(dept));
                    if (ObjectUtil.isNotEmpty(dept)) {
                        String localDeptPid = dept.getLocalDeptPid();
                        if (StringUtils.isNotBlank(localDeptPid)) {
                            Dept localDept = (Dept) Client.rpcInvoke("hcn.department", "getDeptByLocalDeptId", "61caaf61f5b2ba00a46fe46c", localDeptPid);
                            log.info("localDeptPid=====》" + JSONUtils.writeValueAsString(localDept));
                            if (ObjectUtil.isNotEmpty(localDept)) {
                                response.setDeptPid(localDept.getLocalDeptId());
                                response.setDeptPidName(localDept.getName());

                                List<SurveyPlanWorkListResponse> surveyPlanWorkListResponses = map.get(localDept.getLocalDeptId());
                                if (CollectionUtils.isEmpty(surveyPlanWorkListResponses)) {
                                    List<SurveyPlanWorkListResponse> s1 = new ArrayList<>();
                                    s1.add(response);
                                    map.put(localDept.getLocalDeptId(), s1);
                                } else {
                                    surveyPlanWorkListResponses.add(response);
                                    map.put(localDept.getLocalDeptId(), surveyPlanWorkListResponses);
                                }

//                                List<SurveyPlanWorkListResponse> surveyPlanWorkListResponses = returnResponse.getSurveyPlanWorkListResponses();
//                                if (CollectionUtils.isEmpty(surveyPlanWorkListResponses)){
//                                    List<SurveyPlanWorkListResponse> s1 = new ArrayList<>();
//                                    s1.add(response);
//                                    returnResponse.setSurveyPlanWorkListResponses(s1);
//                                    returnResponse.setDeptPid(localDept.getLocalDeptId());
//                                    returnResponse.setDeptPidName(localDept.getName());
//                                }else {
//                                    surveyPlanWorkListResponses.add(response);
//                                    returnResponse.setSurveyPlanWorkListResponses(surveyPlanWorkListResponses);
//                                    returnResponse.setDeptPid(localDept.getLocalDeptId());
//                                    returnResponse.setDeptPidName(localDept.getName());
//                                }
//                                log.info("returnResponse=====》" + JSONUtils.writeValueAsString(returnResponse));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("调用部门服务异常", e);
            }
        }
        for (String key : map.keySet()) {
            SurveyPlanWorkListResponseNew snew = new SurveyPlanWorkListResponseNew();
            snew.setDepartmentId(key);
            snew.setDepartmentName(map.get(key).get(0).getDeptPidName());
            snew.setSurveyPlanWorkListResponses(map.get(key));
            returnResponse.add(snew);
        }
        return returnResponse;
    }


    /**
     * 满意度工作统计列表
     *
     * @param request
     * @return
     */
    @RpcService(timeout = 60)
    public List<SurveyPlanWorkListResponse> queryStatisticsWorkListNew1(QuerySurveyDeptListRequest request) throws ControllerException {
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        if (CommonUtils.isEmpty(request.getQuestionnaireId())) {
            return planWorkListResponses;
        }
        QueryDeptTotalResponse queryDeptTotalResponse = patientSatisfactionSurveyDAO.queryDeptTotal(request);
//        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())){
//            queryDeptTotalResponse.setTotalSum("0");
//        }else {
//            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
//            queryDeptTotalResponse.setTotalSum(String.valueOf(new BigDecimal(new Double(0)*100).setScale(2,RoundingMode.HALF_UP)));
//        }
        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())) {

            queryDeptTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDeptTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }
        log.info("==========================科室评价统计" + JSONUtils.writeValueAsString(queryDeptTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.querySurveyDeptByDeptIdNew(request);
        log.info("查询输出打印=======================================》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponses));
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDepartmentId(surveyPlanDeptListResponse.getDepartmentId());
            response.setDepartmentName(surveyPlanDeptListResponse.getDepartmentName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            log.info("科室======》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponse.getC()));
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }

            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            BigDecimal d = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getD())) {
                d = new BigDecimal(new Double(0) * 100);

            } else {
                d = new BigDecimal(surveyPlanDeptListResponse.getD() * 100);
            }

            BigDecimal dmum = d.setScale(2, RoundingMode.HALF_UP);
            response.setD(String.valueOf(dmum));


            BigDecimal e = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getE())) {
                e = new BigDecimal(new Double(0) * 100);

            } else {
                e = new BigDecimal(surveyPlanDeptListResponse.getE() * 100);
            }

            BigDecimal Emum = e.setScale(2, RoundingMode.HALF_UP);
            response.setE(String.valueOf(Emum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDepartmentId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDeptId(surveyPlanDeptListResponse.getDepartmentId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                // List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDeptId(req);
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            response.setQueryDeptTotalResponse(queryDeptTotalResponse);
            log.info("前端相应输出=====》" + JSONUtils.writeValueAsString(response));
            planWorkListResponses.add(response);

        }

        return planWorkListResponses;
    }

    /**
     * 满意度工作统计列表
     *
     * @param request
     * @return
     */
    @RpcService(timeout = 60)
    public List<SurveyPlanWorkListResponse> queryStatisticsWorkList(QuerySurveyDeptListRequest request) throws ControllerException {
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        if (CommonUtils.isEmpty(request.getQuestionnaireId())) {
            return planWorkListResponses;
        }
        QueryDeptTotalResponse queryDeptTotalResponse = patientSatisfactionSurveyDAO.queryDeptTotal(request);
//        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())){
//            queryDeptTotalResponse.setTotalSum("0");
//        }else {
//            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
//            queryDeptTotalResponse.setTotalSum(String.valueOf(new BigDecimal(new Double(0)*100).setScale(2,RoundingMode.HALF_UP)));
//        }
        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())) {

            queryDeptTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDeptTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }
        log.info("==========================科室评价统计" + JSONUtils.writeValueAsString(queryDeptTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.querySurveyDeptByDeptId(request);
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDepartmentId(surveyPlanDeptListResponse.getDepartmentId());
            response.setDepartmentName(surveyPlanDeptListResponse.getDepartmentName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            log.info("科室======》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponse.getC()));
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }

            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDepartmentId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDeptId(surveyPlanDeptListResponse.getDepartmentId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                // List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDeptId(req);
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            response.setQueryDeptTotalResponse(queryDeptTotalResponse);
            planWorkListResponses.add(response);

        }

        return planWorkListResponses;
    }


    /**
     * 满意度医生统计列表
     *
     * @param request
     * @return
     */
    @RpcService
    public List<SurveyPlanWorkListResponse> queryDoctorWorkList(QuerySurveyDeptListRequest request) throws ControllerException {
        request.setNewDeptId(Arrays.asList(request.getDeptId().split(",")).stream().map(x -> String.valueOf(x)).collect(Collectors.toList()));
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        if (CommonUtils.isEmpty(request.getQuestionnaireId())) {
            return planWorkListResponses;
        }
        log.info(JSONUtils.writeValueAsString(request));
        QueryDoctorTotalResponse queryDoctorTotalResponse = patientSatisfactionSurveyDAO.queryDoctorWorkListTotal(request);
        if (CommonUtils.isNull(queryDoctorTotalResponse.getTotalSum())) {

            queryDoctorTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDoctorTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDoctorTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }

        log.info("---------------------------------》统计" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.queryDoctorWorkList1(request);
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
            response.setDoctorName(surveyPlanDeptListResponse.getDoctorName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }
            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDoctorId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            log.info("---------------------------------》统计--------------------->" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
            response.setQueryDoctorTotalResponse(queryDoctorTotalResponse);
            planWorkListResponses.add(response);
        }
        return planWorkListResponses;
    }

    /**
     * 满意度医生统计列表SatisfactionSurveyExcelService
     *
     * @param request
     * @return
     */
    @RpcService
    public List<SurveyPlanWorkListResponse> queryDoctorWorkListNew(QuerySurveyDeptListRequest request) throws ControllerException {
        request.setNewDeptId(Arrays.asList(request.getDeptId().split(",")).stream().map(x -> String.valueOf(x)).collect(Collectors.toList()));
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        if (CommonUtils.isEmpty(request.getQuestionnaireId())) {
            return planWorkListResponses;
        }
        log.info(JSONUtils.writeValueAsString(request));
        QueryDoctorTotalResponse queryDoctorTotalResponse = patientSatisfactionSurveyDAO.queryDoctorWorkListTotal(request);
        if (CommonUtils.isNull(queryDoctorTotalResponse.getTotalSum())) {

            queryDoctorTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDoctorTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDoctorTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }

        log.info("---------------------------------》统计" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.queryDoctorWorkListNew(request);
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
            response.setDoctorName(surveyPlanDeptListResponse.getDoctorName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }
            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));


            BigDecimal a = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getD())) {
                a = new BigDecimal(new Double(0) * 100);

            } else {
                a = new BigDecimal(surveyPlanDeptListResponse.getD() * 100);
            }
            BigDecimal anum = a.setScale(2, RoundingMode.HALF_UP);
            response.setD(String.valueOf(anum));

            BigDecimal b = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getE())) {
                b = new BigDecimal(new Double(0) * 100);

            } else {
                b = new BigDecimal(surveyPlanDeptListResponse.getE() * 100);
            }
            BigDecimal bnum1 = b.setScale(2, RoundingMode.HALF_UP);
            response.setE(String.valueOf(bnum1));


            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDoctorId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            log.info("---------------------------------》统计--------------------->" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
            response.setQueryDoctorTotalResponse(queryDoctorTotalResponse);
            planWorkListResponses.add(response);
        }
        return planWorkListResponses;
    }


    /**
     * 满意度调查统计详情
     *
     * @param request
     * @return
     */
    @RpcService
    @RpcAccess(auth = false)
    public SurveyPlanDetailResponse getStatisticsDetail(SurveyPlanDetailRequest request) {
        SurveyPlanDetailResponse response = new SurveyPlanDetailResponse();
        PatientSatisfactionSurvey patientSatisfactionSurvey = patientSatisfactionSurveyDAO.get(request.getPatientSurveyId());
        if (CommonUtils.isNotEmpty(patientSatisfactionSurvey)) {
            org.springframework.beans.BeanUtils.copyProperties(patientSatisfactionSurvey, response);
            //查询门诊诊断等
            queryBusinessData(response);
            //查询健康宣教列表，查询问卷列表
            List<SatisfactionHealthEducation> eList = satisfactionHealthEducationDAO.queryByPatientSurveyId(patientSatisfactionSurvey.getPatientSurveyId());
            if (!CollectionUtils.isEmpty(eList)) {
                List<FollowUpEducationVO> collect = eList.stream().map(e -> {
                    Long educationId = e.getEducationId();
                    FusHealthEducationEntity f = fusHealthEducationDAO.get(educationId);
                    if (!Objects.isNull(f)) {
                        FollowUpEducationVO vo = new FollowUpEducationVO();
                        vo.setId(e.getId());
                        vo.setEducationId(e.getEducationId());
                        vo.setEducationName(e.getEducationName());
                        vo.setContent(f.getContent());
                        return vo;
                    }
                    return null;
                }).filter(Objects::nonNull).collect(Collectors.toList());
                response.setSatisfactionHealthEducationList(collect);
            }
            response.setSatisfactionRequisitionRecordList(satisfactionRequisitionRecordDAO.queryByPatientSurveyId(patientSatisfactionSurvey.getPatientSurveyId()));
        }
        List<SurveyPlanDetailResponse.TitleBean> list = patientSatisfactionSurveyDAO.queryTeamSurveyRecordList(request);
        response.setTitleList(list);

        if (CommonUtils.isNotEmpty(list)) {
            List<SurveyPlanDetailResponse.Questionnaire> questionnaireList = new ArrayList<>();
            for (SurveyPlanDetailResponse.TitleBean titleBean : list) {
                SurveyPlanDetailResponse.Questionnaire questionnaire = null;
                for (SurveyPlanDetailResponse.Questionnaire elem : questionnaireList) {
                    if (titleBean.getQuestionnaireId().equals(elem.getQuestionnaireId())) {
                        questionnaire = elem;
                        break;
                    }
                }

                if (questionnaire == null) {
                    questionnaire = new SurveyPlanDetailResponse.Questionnaire();
                    questionnaire.setQuestionnaireId(titleBean.getQuestionnaireId());
                    questionnaire.setQuestionnaireName(titleBean.getQuestionnaireName());
                    questionnaireList.add(questionnaire);
                }

                List<SurveyPlanDetailResponse.TitleBean> titleBeanList = questionnaire.getTitleBeanList();
                if (titleBeanList == null) {
                    titleBeanList = new ArrayList<>();
                    questionnaire.setTitleBeanList(titleBeanList);
                }
                titleBeanList.add(titleBean);


            }
            response.setQuestionnaireList(questionnaireList);
        }

        String doctorId = response.getDoctorId();
        String organizationId = response.getOrganizationId();
        String personCodeById = getPersonCodeById(doctorId, organizationId);
        if (StringUtils.isNotEmpty(personCodeById)) {
            response.setDoctorId(personCodeById);
        }
        String modifyId = response.getModifyId();
        //查询最后编辑人
        if (StringUtils.isNotEmpty(modifyId)) {
            try {
                String modifyName = "";
                DoctInfo docInfo = doctorService.getDocInfo(modifyId);
                if (Objects.nonNull(docInfo)) {
                    modifyName = docInfo.getName();

                }

                String doctorCode = getPersonCode(modifyId);
                if (StringUtils.isNotEmpty(doctorCode)) {
                    modifyName = modifyName + "(" + doctorCode + ")";
                }

                response.setModifyName(modifyName);
            } catch (Exception e) {
                log.error("", e);
            }
        }

        //查询person
        if (!StringUtils.isEmpty(response.getCardNumber()) && !StringUtils.isEmpty(response.getCardType())) {
            //查询personId
            Certificate cert = new Certificate(response.getCardType(), response.getCardNumber(), "01");
            try {
                Person person = mpiProvider.getPersonByCertificate(cert);
                if (Objects.nonNull(person)) {
                    response.setPersonId(person.getMpiId());
                }
            } catch (MPIException e) {
                log.error("获取用户信息失败");
            }
        }

        return response;
    }

    private String getPersonCodeById(String localDocId, String orgId) {
        if (StringUtils.isEmpty(localDocId) || StringUtils.isEmpty(orgId)) {
            return null;
        }
        Organization orgDetailByOrgCode = organizationRpcService.getOrgDetailByOrgCode(orgId);
        if (Objects.isNull(orgDetailByOrgCode)) {
            return null;
        }
        Doctor doctor = doctorService.getDoctorByLocalDoctorIdAndOrgId(localDocId, orgDetailByOrgCode.getOrgId());
        if (Objects.isNull(doctor)) {
            return null;
        }
        return getPersonCode(doctor.getDoctorId());
    }

    private String getPersonCode(String docId) {
        String doctorUserId = docIdentityService.getDoctorUserId(docId);
        //用doctorUserId拿到personInfo，根据personInfo中的字典值cd拿到医生编码
        Map<String, Object> personInfo = AppContextHolder.get().getBean(IPersonService.class).getByUserId(doctorUserId);
        if (CommonUtils.isNotEmpty(personInfo)) {
            return (String) personInfo.get("cd");
        }
        return null;
    }

    private void queryBusinessData(SurveyPlanDetailResponse survey) {
        Byte businessType = Byte.valueOf(survey.getBusinessType());
        String businessId = survey.getBusinessId();
        VisitRecordEnum visitType = VisitRecordEnum.getEnumByKey(businessType);
        String patientSurveyId = survey.getPatientSurveyId();
        List<String> dataList = new ArrayList<>();
        Date bizDate = null;
        switch (visitType) {
            case OUTPATIENT_VISIT_RECORD:
                //门诊诊断
                VrOutpatientVisitRecord vrOutpatientVisitRecord = vrOutpatientVisitRecordDAO.get(businessId);
                if (Objects.nonNull(vrOutpatientVisitRecord)) {
                    bizDate = vrOutpatientVisitRecord.getStartTime();
                }
                List<VrVisitDiagnosis> vrVisitDiagnoses = vrVisitDiagnosisDAO.queryVrVisitDiagnosis(businessId);
                if (!CollectionUtils.isEmpty(vrVisitDiagnoses)) {
                    dataList = vrVisitDiagnoses.stream().map(VrVisitDiagnosis::getDiseasesName).collect(Collectors.toList());
                }
                break;
            case INPATIENT_VISIT_RECORD:
                //住院诊断
                VrInpatientVisitRecord inpatientVisitRecord = vrInpatientVisitRecordDAO.get(businessId);
                if (Objects.nonNull(inpatientVisitRecord)) {
                    bizDate = inpatientVisitRecord.getDischargeTime();
                }
                List<VrVisitDiagnosis> inVisitDiagnoses = vrVisitDiagnosisDAO.queryVrVisitDiagnosis(businessId);
                if (!CollectionUtils.isEmpty(inVisitDiagnoses)) {
                    dataList = inVisitDiagnoses.stream().map(VrVisitDiagnosis::getDiseasesName).collect(Collectors.toList());
                }
                break;
            case PHYSICAL_EXAMINATION_RECORDS:
                break;
            case SURGICAL_RECORD:
                VrSurgicalRecord vrSurgicalRecord = vrSurgicalRecordDAO.get(businessId);
                if (Objects.nonNull(vrSurgicalRecord)) {
                    bizDate = vrSurgicalRecord.getStartTime();
                    dataList = Collections.singletonList(vrSurgicalRecord.getOperationName());
                }
                break;
            case INSPECTION_RECORD:
                //检验
                VrApplicationFormRecord q1 = new VrApplicationFormRecord();
                q1.setApplicationId(businessId);
                q1.setBillCategoryCode("1");
                VrApplicationFormRecord v1 = vrApplicationFormRecordDAO.selectOneWithLimit(q1, "");
                if (Objects.nonNull(v1)) {
                    bizDate = v1.getExecutiveTime();
                    dataList = getApplicationItemNameList(v1.getApplicationId());
                }
                break;
            case CHECK_RECORD:
                //检查
                VrApplicationFormRecord q2 = new VrApplicationFormRecord();
                q2.setApplicationId(businessId);
                q2.setBillCategoryCode("2");
                VrApplicationFormRecord v2 = vrApplicationFormRecordDAO.selectOneWithLimit(q2, "");
                if (Objects.nonNull(v2)) {
                    bizDate = v2.getExecutiveTime();
                    dataList = getApplicationItemNameList(v2.getApplicationId());
                }
                break;
            case DISPENSING_RECORD:
                //取药
                VrDispensingRecord qd = new VrDispensingRecord();
                qd.setDistributionId(businessId);
                VrDispensingRecord vrDispensingRecord = vrDispensingRecordDAO.selectOneWithLimit(qd, "");
                if (Objects.nonNull(vrDispensingRecord)) {
                    //todo 没有名字
                    bizDate = vrDispensingRecord.getDispensingDate();
//                    dataList = Collections.singletonList(vrDispensingRecord.get);
                }
                break;
            case TREATMENT_RECORD:
                //治疗 3
                VrApplicationFormRecord q3 = new VrApplicationFormRecord();
                q3.setApplicationId(businessId);
                q3.setBillCategoryCode("3");
                VrApplicationFormRecord v3 = vrApplicationFormRecordDAO.selectOneWithLimit(q3, "");
                if (Objects.nonNull(v3)) {
                    bizDate = v3.getExecutiveTime();
                    dataList = getApplicationItemNameList(v3.getApplicationId());
                }
                break;
            default:
                break;
        }
        survey.setBusinessTime(bizDate);
        survey.setBusinessItemNames(dataList);
    }

    /**
     * 获取检查\检验单项目
     */
    private List<String> getApplicationItemNameList(String applicationId) {
        List<VrApplicationFormDetail> afd = vrApplicationFormDetailDAO.queryDetailByApplicationId(applicationId);
        if (!CollectionUtils.isEmpty(afd)) {
            return afd.stream().map(VrApplicationFormDetail::getItemName).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 暂挂
     */
    @RpcService
    public void hangUpPlan(FollowUpHangUpDTO dto) {
        //增加暂挂记录
        FusAfterPendingRecord insert = new FusAfterPendingRecord();
        insert.setId(KeyGenerator.randomGenerate());
        insert.setRecordId(dto.getRecordId());
        insert.setFollowType(FollowTypeEnum.FUS_SPECIALIST.getType());
        insert.setExecuteId(dto.getExecuteId());
        insert.setExecuteName(dto.getExecuteName());
        insert.setDepartmentId(dto.getExecuteDeptId());
        insert.setDeptName(dto.getExecuteDeptName());
        insert.setPendingType(dto.getPendingType());
        insert.setPendingDetail(dto.getExecuteDetail());
        insert.setCreateDt(new Date());
        insert.setModifyDt(new Date());
        fusAfterPendingRecordDAO.insertSelective(insert);
    }

    /**
     * 获取暂挂列表
     *
     * @param recordId 随访记录id
     */
    @RpcService
    public List<HangUpFollowUpListVO> hangUpRecords(String recordId) {

        if (org.springframework.util.StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        FusAfterPendingRecord query = new FusAfterPendingRecord();
        query.setRecordId(recordId);
        query.setFollowType(FollowTypeEnum.FUS_SPECIALIST.getType());
        List<FusAfterPendingRecord> records = fusAfterPendingRecordDAO.selectList(query);
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        return records.stream().map(r -> {
            HangUpFollowUpListVO vo = new HangUpFollowUpListVO();
            ctd.util.BeanUtils.copy(r, vo);
            return vo;
        }).sorted((r1, r2) -> {
            Date createDt1 = r1.getCreateDt();
            Date createDt2 = r2.getCreateDt();
            return createDt1.compareTo(createDt2);
        }).collect(Collectors.toList());
    }

    /**
     * 完成随访计划
     */
    @RpcService
    public void finishPlan(FollowUpFinishDTO dto) {
        //更新主表数据
        String recordId = dto.getRecordId();

        PatientSatisfactionSurvey update = new PatientSatisfactionSurvey();
        update.setPatientSurveyId(recordId);
        //已完成
        update.setSurveyStatus("1");
        patientSatisfactionSurveyDAO.updateSelective(update);

        PatientSatisfactionSurvey patientSatisfactionSurvey = patientSatisfactionSurveyDAO.get(recordId);
        if (Objects.isNull(patientSatisfactionSurvey)) {
            return;
        }
        //非更新调查的情况下才更新完成调查次数
        updateFinishNumber(patientSatisfactionSurvey.getBusinessType(),
                patientSatisfactionSurvey.getBusinessId());
    }

    /**
     * 取消随访计划
     */
    @RpcService
    public void cancelPlan(FollowUpCancelDTO dto) {
        List<String> recordIds = dto.getRecordIds();
        recordIds.forEach(id -> {
            PatientSatisfactionSurvey update = new PatientSatisfactionSurvey();
            update.setPatientSurveyId(id);
            update.setSurveyStatus("9");
            patientSatisfactionSurveyDAO.updateSelective(update);
        });
    }

    /**
     * 取消所有随访计划
     */
    @RpcService
    public void cancelAllPlan(FollowUpCancelAllDTO dto) {
        String patientId = dto.getPatientId();
        String organizationId = dto.getOrganizationId();

        PatientSatisfactionSurvey query = new PatientSatisfactionSurvey();
        query.setPatientId(patientId);
        query.setOrganizationId(organizationId);
        query.setSurveyStatus("0");
        List<PatientSatisfactionSurvey> surveys = patientSatisfactionSurveyDAO.selectList(query);
        if (!CollectionUtils.isEmpty(surveys)) {
            surveys.forEach(survey -> {
                String patientSurveyId = survey.getPatientSurveyId();
                PatientSatisfactionSurvey update = new PatientSatisfactionSurvey();
                update.setPatientSurveyId(patientSurveyId);
                update.setSurveyStatus("9");
                patientSatisfactionSurveyDAO.updateSelective(update);
            });
        }
    }

    /**
     * @param businessType
     * @param businessId
     * @throws
     * @description: 更新完成调查次数
     * @return: void
     * @author: tongtp
     * @date: 2020/9/4 16:06
     */
    private void updateFinishNumber(String businessType, String businessId) {
        VisitRecordEnum enumByKey = getEnumByKey(businessType);
        if (enumByKey != null) {
            switch (enumByKey) {
                case OUTPATIENT_VISIT_RECORD:
                    VrOutpatientVisitRecord vrOutpatientVisitRecord =
                            vrOutpatientVisitRecordDAO.get(businessId);
                    if (vrOutpatientVisitRecord != null) {
                        vrOutpatientVisitRecord.setSatisfactionStatus("1");
                        vrOutpatientVisitRecord.setFinishNumber(vrOutpatientVisitRecord.getFinishNumber() + 1);
                        vrOutpatientVisitRecordDAO.update(vrOutpatientVisitRecord);
                    }
                    break;
                case INPATIENT_VISIT_RECORD:
                    VrInpatientVisitRecord vrInpatientVisitRecord =
                            vrInpatientVisitRecordDAO.get(businessId);
                    if (vrInpatientVisitRecord != null) {
                        vrInpatientVisitRecord.setSatisfactionStatus("1");
                        vrInpatientVisitRecord.setFinishNumber(vrInpatientVisitRecord.getFinishNumber() + 1);
                        vrInpatientVisitRecordDAO.update(vrInpatientVisitRecord);
                    }
                    break;
                case SURGICAL_RECORD:
                    VrSurgicalRecord vrSurgicalRecord =
                            vrSurgicalRecordDAO.get(businessId);
                    if (vrSurgicalRecord != null) {
                        vrSurgicalRecord.setSatisfactionStatus("1");
                        vrSurgicalRecord.setFinishNumber(vrSurgicalRecord.getFinishNumber() + 1);
                        vrSurgicalRecordDAO.update(vrSurgicalRecord);
                    }
                    break;
                case INSPECTION_RECORD:
                case CHECK_RECORD:
                case TREATMENT_RECORD:
                    VrApplicationFormRecord vrApplicationFormRecord =
                            vrApplicationFormRecordDAO.get(businessId);
                    if (vrApplicationFormRecord != null) {
                        vrApplicationFormRecord.setSatisfactionStatus("1");
                        vrApplicationFormRecord.setFinishNumber(vrApplicationFormRecord.getFinishNumber() + 1);
                        vrApplicationFormRecordDAO.update(vrApplicationFormRecord);
                    }
                    break;
                case DISPENSING_RECORD:
                    VrDispensingRecord vrDispensingRecord =
                            vrDispensingRecordDAO.get(businessId);
                    if (vrDispensingRecord != null) {
                        vrDispensingRecord.setSatisfactionStatus("1");
                        vrDispensingRecord.setFinishNumber(vrDispensingRecord.getFinishNumber() + 1);
                        vrDispensingRecordDAO.update(vrDispensingRecord);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 保存随访表单\满意度\健康宣教
     */
    @RpcService
    @Deprecated
    public void saveForm(SaveFollowUpFormDTO dto) throws ControllerException {
        String recordId = dto.getRecordId();
        if (org.springframework.util.StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        UserAllVo userInfo = baseDeviceService.getAllByOnline();
        if (Objects.isNull(userInfo)) {
            throw new ServiceException("获取当前用户信息失败");
        }
        List<FollowUpQuestionnaireDTO> questionnaireList = dto.getQuestionnaireList();
        //保存随访表单
        if (!CollectionUtils.isEmpty(questionnaireList)) {
            //TODO 如果随访已完成 则不允许新增和修改 针对医护随访
            PatientSatisfactionSurvey satisfactionSurvey = patientSatisfactionSurveyDAO.get(recordId);
            if (FollowUpStatusEnum.FINISH.getStatus() == Byte.parseByte(satisfactionSurvey.getSurveyStatus())) {
                throw new ControllerException("随访计划已完成，不可进行表单新增或更新");
            } else {
                if (RouteDetailTypeEnum.WJSF.getType().equals(satisfactionSurvey.getRouteDetailType().toString())) {
                    //判断问卷是否已填写，已经填写则不能进行新增和修改
                    if (SurveyStatusEnum.FILL_IN.getStatus().equals(satisfactionSurvey.getSurveyStatus())) {
                        throw new ControllerException("问卷随访已经完成，不可进行表单新增或更新");
                    }
                }
            }
            questionnaireList.forEach(q -> saveOrUpdateQuestionnaire(q, userInfo, recordId));
        }

        //保存健康宣教
        List<FollowUpEducationDTO> educationList = dto.getEducationList();
        if (!CollectionUtils.isEmpty(educationList)) {
            educationList.forEach(e -> saveOrUpdateEducation(e, recordId));
        }

    }

    /**
     * 保存随访表单
     */
    private void saveOrUpdateQuestionnaire(FollowUpQuestionnaireDTO dto, UserAllVo userInfo, String recordId) {
        String formId = dto.getFormId();
        Date now = new Date();
        SatisfactionRequisitionRecord insertOrUpdate = new SatisfactionRequisitionRecord();

        insertOrUpdate.setRecordId(recordId);
        insertOrUpdate.setCreateId(userInfo.getUserId());
        insertOrUpdate.setExecuteId(userInfo.getUserId());
        insertOrUpdate.setExecuteName(userInfo.getUserName());

        String questionnaireId = dto.getQuestionnaireId();
        if (org.springframework.util.StringUtils.isEmpty(questionnaireId)) {
            return;
        }
        insertOrUpdate.setQuestionnaireId(questionnaireId);
        insertOrUpdate.setQuestionnaireName(dto.getQuestionnaireName());
        insertOrUpdate.setUserInfoId(dto.getUserInfoId());
        insertOrUpdate.setSurveyTime(now);
        insertOrUpdate.setSurveyName(userInfo.getUserId());
        insertOrUpdate.setSurveyId(userInfo.getUserName());
        insertOrUpdate.setAnswerAbnormal(dto.getAnswerAbnormal());
        insertOrUpdate.setSurveyStatus(SurveyStatusEnum.FILL_IN.getStatus());

        if (org.springframework.util.StringUtils.isEmpty(formId)) {
            //新增
            insertOrUpdate.setFormId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            insertOrUpdate.setModifyDt(now);
            insertOrUpdate.setSurveyStatus(SurveyStatusEnum.NOT_FILLED_IN.getStatus());
            satisfactionRequisitionRecordDAO.insertSelective(insertOrUpdate);
        } else {
            //更新
            insertOrUpdate.setFormId(formId);
            insertOrUpdate.setModifyDt(now);
            satisfactionRequisitionRecordDAO.updateSelective(insertOrUpdate);
        }
    }

    /**
     * 保存健康宣教
     */
    private void saveOrUpdateEducation(FollowUpEducationDTO dto, String recordId) {
        String id = dto.getId();
        SatisfactionHealthEducation insertOrUpdate = new SatisfactionHealthEducation();
        Long educationId = dto.getEducationId();
        if (Objects.isNull(educationId)) {
            return;
        }
        insertOrUpdate.setEducationId(educationId);
        insertOrUpdate.setRecordId(recordId);
        insertOrUpdate.setDefaultPush(0);
        insertOrUpdate.setEducationName(dto.getEducationName());

        Date now = new Date();
        insertOrUpdate.setModifyDt(now);
        if (org.springframework.util.StringUtils.isEmpty(id)) {
            insertOrUpdate.setId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            satisfactionHealthEducationDAO.insertSelective(insertOrUpdate);
        } else {
            insertOrUpdate.setId(id);
            satisfactionHealthEducationDAO.updateSelective(insertOrUpdate);
        }
    }

    /**
     * 删除健康宣教 删除随访表单 删除满意度调查
     */
    @RpcService
    @Deprecated
    public void deleteForm(DeleteFollowUpFormDTO dto) throws ControllerException {
        String formId = dto.getFormId();
        String eduFormId = dto.getEduFormId();
        if (StringUtils.isNotEmpty(formId)) {
            SatisfactionRequisitionRecord requisitionRecord = satisfactionRequisitionRecordDAO.get(formId);
            PatientSatisfactionSurvey satisfactionSurvey = patientSatisfactionSurveyDAO.get(requisitionRecord.getRecordId());
            if (CommonUtils.isNotEmpty(satisfactionSurvey)) {
                if (FollowUpStatusEnum.FINISH.getStatus() == Byte.parseByte(satisfactionSurvey.getSurveyStatus())) {
                    throw new ControllerException("随访计划已完成，不可删除表单");
                } else {
                    if (RouteDetailTypeEnum.WJSF.getType().equals(satisfactionSurvey.getRouteDetailType().toString())) {
                        //判断问卷是否已填写，已经填写则不能进行删除
                        if (SurveyStatusEnum.FILL_IN.getStatus().equals(satisfactionSurvey.getSurveyStatus())) {
                            throw new ControllerException("问卷随访已经完成，不可删除表单");
                        }
                    }
                }
            }
            satisfactionRequisitionRecordDAO.remove(formId);
        }
        if (!org.springframework.util.StringUtils.isEmpty(eduFormId)) {
            satisfactionHealthEducationDAO.remove(eduFormId);
        }
    }

    /**
     * 查询问卷处理部门列表
     *
     * @param request
     * @return
     */
    @RpcService
    public List<SurveyDepartmentListResponse> querySurveyDepartmentList(SurveyDepartmentListRequest request) {
        List<SurveyDepartmentListResponse> response = new ArrayList<>();
        try {
            QueryAllDocTeamReq req = new QueryAllDocTeamReq();
            List<DocTeamEntity> docTeamEntityList = docTeamRpcService.queryAllDocTeam(req);
            if (CommonUtils.isNotEmpty(docTeamEntityList)) {
                List<Long> collect = docTeamEntityList.stream().map(DocTeamEntity::getMedicalTeamId).collect(Collectors.toList());
                log.info("collect" + JSONArray.toJSON(collect));
                List<SurveyDepartmentListResponse> surveyDepartmentListResponses =
                        patientSatisfactionSurveyDAO.querySurveyDepartmentList(request);
                if (!CollectionUtils.isEmpty(surveyDepartmentListResponses)) {
                    //去除题目的HTML标签
                    for (SurveyDepartmentListResponse surveyDepartmentListResponse :
                            surveyDepartmentListResponses) {
                        if (collect.contains(surveyDepartmentListResponse.getMedicalTeamId())) {
                            surveyDepartmentListResponse.setTitleName(Utils.Html2Text(surveyDepartmentListResponse.getTitleName()));
                            response.add(surveyDepartmentListResponse);
                        }

                    }
                }
            }
        } catch (ControllerException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 调查统计详情发起处理 todo linyi
     *
     * @param request
     */
    @RpcService
    public void saveTeamSurveyRecord(SaveTeamSurveyRecordRequest request) throws ControllerException {
        List<String> patientSurveyIds = request.getPatientSurveyIds();
        String questionnaireId = request.getQuestionnaireId();
        List<SaveTeamSurveyRecordRequest.TitleBean> titleList = request.getTitleList();
        if (patientSurveyIds != null && patientSurveyIds.size() > 0) {
            PatientSatisfactionSurveyAnswer surveyAnswer;
            for (int i = 0; i < patientSurveyIds.size(); i++) {
                String patientSurveyId = patientSurveyIds.get(i);

                if (titleList != null && titleList.size() > 0) {
                    for (SaveTeamSurveyRecordRequest.TitleBean titleBean : titleList) {
                        TeamSurveyRecord teamSurveyRecord = createTeamSurveyRecordBean(request, titleBean);
                        teamSurveyRecord.setPatientSurveyId(patientSurveyId);
                        surveyAnswer = satisfactionSurveyAnswerDAO.getSurveyAnswerBySqtId(patientSurveyId, questionnaireId, titleBean.getTitleId());
                        if (surveyAnswer != null) {
                            teamSurveyRecord.setAnswerId(surveyAnswer.getAnswerId());
                            teamSurveyRecord.setAnswerName(surveyAnswer.getAnswerName());
                            teamSurveyRecord.setPatientSurveyName(surveyAnswer.getPatientSurveyName());
                            teamSurveyRecordDAO.save(teamSurveyRecord);
                            satisfactionSurveyAnswerDAO.updatePendingStatusById(surveyAnswer.getSurveyAnswerId());
                        }
                    }
                    //处理表单状态
                    SatisfactionRequisitionRecord q = new SatisfactionRequisitionRecord();
                    q.setRecordId(patientSurveyId);
                    q.setQuestionnaireId(questionnaireId);
                    SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(q, "");
                    if (Objects.nonNull(record)) {
                        SatisfactionRequisitionRecord update = new SatisfactionRequisitionRecord();
                        update.setFormId(record.getFormId());
                        //处理中
                        update.setSurveyStatus("2");
                        satisfactionRequisitionRecordDAO.updateSelective(update);
                    }
                    patientSatisfactionSurveyDAO.updateProcessingStatusAndUserInfoById(patientSurveyId, "1", request.getUserId(), request.getUserName());
                }
            }
            //todo 发起处理推送给医生所在部门的医生
            if (titleList != null && titleList.size() > 0) {
                for (SaveTeamSurveyRecordRequest.TitleBean titleBean : titleList) {
                    List<SatisfactionDoctorPushVo> doctorList = docTeamMemberRpcService.queryMedicalTeamDoctorList(titleBean.getMedicalTeamId());
                    if (doctorList != null && doctorList.size() > 0) {
                        String content = "";
                        SatisfactionDoctorPushVo satisfactionDoctor = new SatisfactionDoctorPushVo();
                        DoctorListQo doctorListQo = new DoctorListQo();
                        doctorListQo.setDepartmentId(doctorList.get(0).getDepartmentId());
                        doctorListQo.setOrganizationId(doctorList.get(0).getOrganizationId());
                        if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
                            List<DoctorInfo> doctorInfos = this.queryDoctorUserIdList(doctorListQo);
                            if (CommonUtils.isNotEmpty(doctorInfos)) {
                                List<DoctorInfo> unique1 = removeDuplicate(doctorInfos);
                                for (DoctorInfo docs : doctorInfos) {
                                    SendMsgRequest sendMsgRequest = new SendMsgRequest();
                                    sendMsgRequest.setHospitalCode(doctorList.get(0).getOrganizationId());
                                    sendMsgRequest.setType(projectSource);
                                    sendMsgRequest.setDoctorId(docs.getDoctorId());
                                    content = docs.getDoctorName() + "您好，有一条新的患者调查处理，点击查看详情。";
                                    satisfactionDoctor.setDoctorId(docs.getDoctorId());
                                    satisfactionDoctor.setDoctorName(docs.getDoctorName());
                                    SatisfactionDoctorPushThread doctorPushThread = new SatisfactionDoctorPushThread(satisfactionDoctor, sendMsgRequest, sendMsgService, docs.getUserId(), content, 0, 1);
                                    doctorPushThread.run();
                                }
                            }
                        } else if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
                            List<DoctorListVo> doctorInfos = this.queryDoctorUserIdHolList(doctorListQo);
                            if (CommonUtils.isNotEmpty(doctorInfos)) {
                                for (DoctorListVo docs : doctorInfos) {
                                    SendMsgRequest sendMsgRequest = new SendMsgRequest();
                                    sendMsgRequest.setHospitalCode(doctorList.get(0).getOrganizationId());
                                    sendMsgRequest.setType(projectSource);
                                    sendMsgRequest.setDoctorId(docs.getDoctorId());
                                    content = docs.getDoctorName() + "您好，有一条新的患者调查处理，点击查看详情。";
                                    satisfactionDoctor.setDoctorId(docs.getDoctorId());
                                    satisfactionDoctor.setDoctorName(docs.getDoctorName());
                                    SatisfactionDoctorPushThread doctorPushThread = new SatisfactionDoctorPushThread(satisfactionDoctor, sendMsgRequest, sendMsgService, "", content, 0, 1);
                                    doctorPushThread.run();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取医生的userId GOL
     *
     * @param doctorListQo
     * @return
     */
    public List<DoctorInfo> queryDoctorUserIdList(DoctorListQo doctorListQo) {
        List<DoctorInfo> doctorInfos = new ArrayList<>();
        BaseResponse<List<DoctorInfo>> baseResponse = baseDataService.queryDoctorUserIdList(doctorListQo);
        if (CommonUtils.isNotEmpty(baseResponse)) {
            if (CommonUtils.isNotEmpty(baseResponse.getData())) {
                doctorInfos = baseResponse.getData();
            }
        }
        return doctorInfos;
    }

    /**
     * 获取医生的userId HOL
     *
     * @param doctorListQo
     * @return
     */
    public List<DoctorListVo> queryDoctorUserIdHolList(DoctorListQo doctorListQo) {
        List<DoctorListVo> doctorInfos = new ArrayList<>();
        BaseResponse<List<DoctorListVo>> baseResponse = baseDataService.queryDoctorList(doctorListQo);
        if (CommonUtils.isNotEmpty(baseResponse)) {
            if (CommonUtils.isNotEmpty(baseResponse.getData())) {
                doctorInfos = baseResponse.getData();
            }
        }
        return doctorInfos;
    }

    private TeamSurveyRecord createTeamSurveyRecordBean(SaveTeamSurveyRecordRequest request, SaveTeamSurveyRecordRequest.TitleBean titleBean) {
        TeamSurveyRecord teamSurveyRecord = new TeamSurveyRecord();
        teamSurveyRecord.setTeamSurveyRecordId(UUID.randomUUID().toString());
        teamSurveyRecord.setQuestionnaireId(request.getQuestionnaireId());
        teamSurveyRecord.setQuestionnaireName(request.getQuestionnaireName());
        teamSurveyRecord.setTitleId(titleBean.getTitleId());
        teamSurveyRecord.setTitleName(titleBean.getTitleName());
        teamSurveyRecord.setMedicalTeamId(titleBean.getMedicalTeamId());
        teamSurveyRecord.setMedicalTeamName(titleBean.getMedicalTeamName());
        teamSurveyRecord.setCreatorId(request.getUserId());
        teamSurveyRecord.setGmtCreate(new Date());
        return teamSurveyRecord;

    }

    /**
     * 查询满意度调查处理计划列表
     *
     * @param request
     */
    @RpcService
    public SurveyDealWithPlanListResponse querySurveyDealWithPlanList(SurveyDealWithPlanListRequest request) throws ControllerException {
        SurveyDealWithPlanListResponse response = new SurveyDealWithPlanListResponse();
        if (StringUtils.isNotEmpty(request.getDocId())) {
            //查询当前登录医生所在团队列表
            List<Long> medicalTeamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
            if (CommonUtils.isNotEmpty(medicalTeamIds)) {
                List<String> patientSurveyIds = teamSurveyRecordDAO.findSurveyIdsByMedicalTeamId(medicalTeamIds);
                request.setPatientSurveyIds(patientSurveyIds);
                List<SurveyDealWithPlanListResponse.DealWithPlanBean> list = patientSatisfactionSurveyDAO.querySurveyDealWithPlanList(request);
                BigInteger total = patientSatisfactionSurveyDAO.getSurveyDealWithPlanCount(request);
                List<SurveyDealWithPlanListResponse.DealWithPlanBean> responseList = new ArrayList<SurveyDealWithPlanListResponse.DealWithPlanBean>();
                if (list != null && list.size() > 0) {
                    for (SurveyDealWithPlanListResponse.DealWithPlanBean dealWithPlanBean : list) {
                        //List<PatientSatisfactionSurveyAnswer> surveyAnswerList =satisfactionSurveyAnswerDAO.queryPendingSurveyAnswerBySurveyId(dealWithPlanBean.getPatientSurveyId());
                        //判断该团队下医生需要处理的问题是否处理完成
                        SurveyDealWithPlanDetailRequest res = new SurveyDealWithPlanDetailRequest();
                        res.setMedicalTeamIds(medicalTeamIds);
                        res.setPatientSurveyId(dealWithPlanBean.getPatientSurveyId());
                        res.setProcessingStatus("1");
                        List<SurveyDealWithPlanDetailResponse.TitleBean> titleBeanList = patientSatisfactionSurveyDAO.getSurveyDealWithPlanDetail(res);
                        if (titleBeanList != null && titleBeanList.size() > 0) {
                            dealWithPlanBean.setProcessingStatus("1");
                            dealWithPlanBean.setProcessingStatusText("待处理");
                        } else {
                            dealWithPlanBean.setProcessingStatus("2");
                            dealWithPlanBean.setProcessingStatusText("已处理");
                        }

                        if (StringUtils.isNotEmpty(request.getProcessingStatus()) && !"0".equals(request.getProcessingStatus())) {
                            if (request.getProcessingStatus().equals(dealWithPlanBean.getProcessingStatus())) {
                                responseList.add(dealWithPlanBean);
                            }
                        } else {
                            responseList.add(dealWithPlanBean);
                        }
                    }
                    response.setTotal(total.intValue() - (list.size() - responseList.size()));
                }
                response.setList(responseList);

            }

        } else {
            BigInteger total = patientSatisfactionSurveyDAO.getSurveyDealWithPlanCount(request);
            if (BigInteger.ZERO.compareTo(total) >= 0) {
                response.setTotal(0);
                return response;
            }
            List<SurveyDealWithPlanListResponse.DealWithPlanBean> list = patientSatisfactionSurveyDAO.querySurveyDealWithPlanList(request);
            List<SurveyDealWithPlanListResponse.DealWithPlanBean> responseList = new ArrayList<SurveyDealWithPlanListResponse.DealWithPlanBean>();
            if (list != null && list.size() > 0) {
                for (SurveyDealWithPlanListResponse.DealWithPlanBean dealWithPlanBean : list) {
                    //List<PatientSatisfactionSurveyAnswer> surveyAnswerList =satisfactionSurveyAnswerDAO.queryPendingSurveyAnswerBySurveyId(dealWithPlanBean.getPatientSurveyId());
                    //判断该团队下医生需要处理的问题是否处理完成
                    SurveyDealWithPlanDetailRequest res = new SurveyDealWithPlanDetailRequest();
                    if (StringUtils.isNotEmpty(request.getDocId())) {
                        List<Long> medicalTeamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
                        res.setMedicalTeamIds(medicalTeamIds);
                    }
                    res.setPatientSurveyId(dealWithPlanBean.getPatientSurveyId());
                    res.setProcessingStatus("1");
                    List<SurveyDealWithPlanDetailResponse.TitleBean> titleBeanList = patientSatisfactionSurveyDAO.getSurveyDealWithPlanDetail(res);
                    if (titleBeanList != null && titleBeanList.size() > 0) {
                        dealWithPlanBean.setProcessingStatus("1");
                        dealWithPlanBean.setProcessingStatusText("待处理");
                    } else {
                        dealWithPlanBean.setProcessingStatus("2");
                        dealWithPlanBean.setProcessingStatusText("已处理");
                    }

                    if (StringUtils.isNotEmpty(request.getProcessingStatus()) && !"0".equals(request.getProcessingStatus())) {
                        if (request.getProcessingStatus().equals(dealWithPlanBean.getProcessingStatus())) {
                            responseList.add(dealWithPlanBean);
                        }
                    } else {
                        responseList.add(dealWithPlanBean);
                    }
                }
                response.setTotal(total.intValue() - (list.size() - responseList.size()));
            }
            response.setList(responseList);
        }
        return response;
    }

    /**
     * 查询满意度调查处理计划详情
     *
     * @param request
     */
    @RpcService
    public SurveyDealWithPlanDetailResponse surveyDealWithPlanDetail(SurveyDealWithPlanDetailRequest request) throws ControllerException {
        SurveyDealWithPlanDetailResponse response = new SurveyDealWithPlanDetailResponse();
        if (StringUtils.isNotEmpty(request.getDocId())) {
            List<Long> medicalTeamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
            request.setMedicalTeamIds(medicalTeamIds);
        }
        List<SurveyDealWithPlanDetailResponse.TitleBean> surveyDealWithPlanList =
                patientSatisfactionSurveyDAO.getSurveyDealWithPlanDetail(request);
        PatientSatisfactionSurvey satisfactionSurvey = patientSatisfactionSurveyDAO.getSatisfactionSurveyById(request.getPatientSurveyId());
        log.info("日志打印==================》" + JSONUtils.writeValueAsString(satisfactionSurvey));
        if (null != satisfactionSurvey) {
            BeanUtils.copy(satisfactionSurvey, response);
        }
        response.setPatientId(satisfactionSurvey.getPatientId()); //病人id
        response.setPatientSex(com.bsoft.gol.hcs.utils.DataUtils.judgeGender(satisfactionSurvey.getCardNumber())); //性别
        int i = DataUtils.countAge(satisfactionSurvey.getCardNumber());

        response.setPatientAge(String.valueOf(i)); //年龄
        response.setPatientMedicalCardNumber(satisfactionSurvey.getPatientId());
        String patientSurveyId = request.getPatientSurveyId();
        SatisfactionRequisitionRecord q = new SatisfactionRequisitionRecord();
        q.setRecordId(patientSurveyId);
        q.setQuestionnaireId(request.getQuestionnaireId());
        SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(q, "");
        if (Objects.nonNull(record)) {
            response.setQuestionnaireName(record.getQuestionnaireName());
        }
        response.setTitleList(surveyDealWithPlanList);

        try {
            List<PatientSatisfactionSurveyAnswer> patientSatisfactionSurveyAnswers = satisfactionSurveyAnswerDAO.queryPendingSurveyAnswerBySurveyId(request.getPatientSurveyId());
            if (!CollectionUtils.isEmpty(patientSatisfactionSurveyAnswers)) {
                for (PatientSatisfactionSurveyAnswer patientSatisfactionSurveyAnswer : patientSatisfactionSurveyAnswers) {
                    if (patientSatisfactionSurveyAnswer.getTitleName().contains("其他建议")) {
                        response.setAnswerName(patientSatisfactionSurveyAnswer.getAnswerName());
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询其他建议异常", e);
        }
        return response;
    }

    @RpcService
    public SurveyDealWithPlanDetailResponse surveyDealWithPlanDetailByDoctor(SurveyDealWithPlanDetailRequest request) throws ControllerException {
        SurveyDealWithPlanDetailResponse response = new SurveyDealWithPlanDetailResponse();
        if (StringUtils.isNotEmpty(request.getDocId())) {
            List<Long> medicalTeamIds = docTeamMemberRpcService.findMedicalTeamIdsByDoctorId(request.getDocId());
            request.setMedicalTeamIds(medicalTeamIds);
        }
        List<SurveyDealWithPlanDetailResponse.TitleBean> surveyDealWithPlanList = patientSatisfactionSurveyDAO.getSurveyDealWithPlanDetailByDoctor(request);
        PatientSatisfactionSurvey satisfactionSurvey = patientSatisfactionSurveyDAO.getSatisfactionSurveyById(request.getPatientSurveyId());
        if (null != satisfactionSurvey) {
            BeanUtils.copy(satisfactionSurvey, response);
        }
        String patientSurveyId = request.getPatientSurveyId();
        SatisfactionRequisitionRecord q = new SatisfactionRequisitionRecord();
        q.setRecordId(patientSurveyId);
        SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(q, "");
        if (Objects.nonNull(record)) {
            response.setQuestionnaireName(record.getQuestionnaireName());
        }
        response.setTitleList(surveyDealWithPlanList);
        return response;
    }

    /**
     * 医生APP/管理端提交满意度调查处理结果
     *
     * @param request
     */
    @RpcService
    public void submitDocSurveyDealWith(SubmitSurveyDealWithRequest request) throws ControllerException {
        if (StringUtils.isEmpty(request.getDocId()) || StringUtils.isEmpty(request.getDoctorName())) {
            throw new ControllerException("处理人工号或姓名不能为空");
        }
        List<SubmitSurveyDealWithRequest.TitleBean> titleBeanList = request.getTitleList();
        if (titleBeanList != null && titleBeanList.size() > 0) {
            for (SubmitSurveyDealWithRequest.TitleBean titleBean : titleBeanList) {
                PatientSatisfactionSurveyAnswer satisfactionSurveyAnswer_exist =
                        satisfactionSurveyAnswerDAO.get(titleBean.getSurveyAnswerId());
                satisfactionSurveyAnswer_exist.setProcessingStatus("2");
                satisfactionSurveyAnswer_exist.setProcessingDoctorId(request.getDoctorId());
                satisfactionSurveyAnswer_exist.setProcessingDoctorName(request.getDoctorName());
                satisfactionSurveyAnswer_exist.setProcessingOpinions(titleBean.getProcessingOpinions());
                satisfactionSurveyAnswer_exist.setNotifyFlag(titleBean.getIsNotify());
                satisfactionSurveyAnswer_exist.setProcessingTime(new Date());
                satisfactionSurveyAnswer_exist.setGmtModified(new Date());
                satisfactionSurveyAnswerDAO.update(satisfactionSurveyAnswer_exist);
            }
            //处理中的题目
//            List<PatientSatisfactionSurveyAnswer> surveyAnswerList = satisfactionSurveyAnswerDAO.queryPendingSurveyAnswerBySurveyId(request.getPatientSurveyId());
            String patientSurveyId = request.getPatientSurveyId();
            //查询出对应的表单 更新表单状态 为已处理 问卷随访是单表单
            SatisfactionRequisitionRecord q = new SatisfactionRequisitionRecord();
            q.setRecordId(patientSurveyId);
            List<SatisfactionRequisitionRecord> satisfactionRequisitionRecords = satisfactionRequisitionRecordDAO.selectList(q);
            if (!CollectionUtils.isEmpty(satisfactionRequisitionRecords)) {
                satisfactionRequisitionRecords.forEach(s -> {
                    SatisfactionRequisitionRecord update = new SatisfactionRequisitionRecord();
                    update.setFormId(s.getFormId());
                    //已处理
                    update.setSurveyStatus("3");
                    update.setModifyDt(new Date());
                    satisfactionRequisitionRecordDAO.updateSelective(update);
                });
            }


            patientSatisfactionSurveyDAO.updateProcessingStatusById(request.getPatientSurveyId(), "2");
            PatientSatisfactionSurvey patientSatisfactionSurvey =
                    patientSatisfactionSurveyDAO.getSatisfactionSurveyById(request.getPatientSurveyId());

            //推送给患者
            if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
                //查询表单
                SatisfactionRequisitionRecord q1 = new SatisfactionRequisitionRecord();
                q1.setRecordId(request.getPatientSurveyId());
                SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(q1, "");
                if (Objects.isNull(record)) {
                    return;
                }
                PushMessageBean pushMessageBean = new PushMessageBean();

                pushMessageBean.setRoleId("patient");
                pushMessageBean.setPatientIdentityCardType(patientSatisfactionSurvey.getCardType());
                pushMessageBean.setPatientIdentityCardNumber(patientSatisfactionSurvey.getCardNumber());
                pushMessageBean.setNotificateType("satisfaction_survey_processed");
                Map<String, String> variableMap = new HashMap<>();
                variableMap.put("jiguang", "极光消息");
                variableMap.put("#回复时间#", DateUtils.toString(patientSatisfactionSurvey.getInitiateTime(), "yyyy-DD-mm HH-mm-ss"));
                //公众号消息模板
                variableMap.put("#Title#", record.getQuestionnaireName());
                variableMap.put("#Number#", record.getQuestionnaireId());//编号
                variableMap.put("#Content#", patientSatisfactionSurvey.getSurveyRuleName());//内容
                variableMap.put("#Time#", patientSatisfactionSurvey.getPlanSurveyTime().toString());//时间
                variableMap.put("#Remarks#", "");//备注
                variableMap.put("#surveyId#", request.getPatientSurveyId());

                String userId = queryUserId(pushMessageBean.getPatientIdentityCardType(), pushMessageBean.getPatientIdentityCardNumber());
                AccessToken accessToken = null;
                try {
                    String url = satisfactionSurveyDistUrl + "#/satisfactionSurvey/mySurveyDetail?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"0\"," +
                            "\"userId\":\"" + patientSatisfactionSurvey.getUserId() + "\",\"userName\":\"" + patientSatisfactionSurvey.getUserName() + "\"}";
                    //获取居民token
                    accessToken = findUserTokenByUserId(userId);
                    if (CommonUtils.isNotEmpty(accessToken)) {
                        url = satisfactionSurveyDistUrl + "#/slowDiseaseManagement/MyApplicationList?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
                                "\"userId\":\"" + patientSatisfactionSurvey.getUserId() + "\",\"userName\":\"" + patientSatisfactionSurvey.getUserName() + "\",\"accessToken\":\"" + accessToken + "\"}";
                    }
                    variableMap.put("#jumpUrl#", url);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("通过userId获取tocken异常：" + e.getMessage());
                }
                pushMessageBean.setMsgVariableMap(variableMap);

                pushMessageBean.setTemplateCode("SATISFACTION_SURVEY_PROCESSED");
                pushMessageBean.setMsgVariableMap(variableMap);

                Map<String, String> extraMap = new HashMap<>();
                extraMap.put("patientSurveyId", request.getPatientSurveyId());
                pushMessageBean.setExtras(extraMap);

                messageSyncService.productionMessage(pushMessageBean);

            } else if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
                SendMsgRequest sendMsgRequest = new SendMsgRequest();
                //TODO 注销推送消息
                sendMsgRequest.setHospitalCode(patientSatisfactionSurvey.getOrganizationId());
                sendMsgRequest.setBusinessType(235);
                sendMsgRequest.setUserType(1);
                sendMsgRequest.setPatientIdentityCardType(patientSatisfactionSurvey.getCardType());
                sendMsgRequest.setPatientIdentityCardNumber(patientSatisfactionSurvey.getCardNumber());
                List<MsgVariable> list = new ArrayList<>();
                MsgVariable msgVariable = new MsgVariable();
                msgVariable.setMsgVariableKey("patientSurveyId");
                msgVariable.setMsgVariableValue(request.getPatientSurveyId());
                list.add(msgVariable);
                sendMsgRequest.setMsgVariableList(list);
                sendMsgService.productionMessage(sendMsgRequest);
            }

            //更新门诊、住院、检验、检查、手术、治疗、取药的已完成调查数量
            if (CommonUtils.isNotEmpty(patientSatisfactionSurvey.getBusinessType()) && CommonUtils.isNotEmpty(patientSatisfactionSurvey.getBusinessId())) {
                //业务类型：1:门诊、2:住院、3:手术、4:检验、5:检查、6:取药、7:治疗记录
                switch (patientSatisfactionSurvey.getBusinessType()) {
                    //门诊
                    case "1":
                        vrOutpatientVisitRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //住院
                    case "2":
                        vrInpatientVisitRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //手术
                    case "3":
                        vrSurgicalRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //检验
                    case "4":
                        vrApplicationFormRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //检查
                    case "5":
                        vrApplicationFormRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //取药
                    case "6":
                        vrDispensingRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                    //治疗
                    case "7":
                        vrApplicationFormRecordDAO.updateFinishNumber(patientSatisfactionSurvey.getBusinessId());
                        break;
                }

            }
        }
    }

    /**
     * 居民提交确认意见
     *
     * @param request
     */
    @RpcService
    public void submitPatientSurveyDealWith(SubmitSurveyDealWithRequest request) {
        patientSatisfactionSurveyDAO.updateConfirmStatusById(request.getPatientSurveyId(), "1");
    }

    /**
     * @description: 查询医生所在团队，所具备满意度规则的科室列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/9/24 12:44
     * @param: request
     * @return: org.atag.core.base.BaseResponse<java.util.List < clinical.bean.vo.DepartmentListVo>>
     */
    @RpcService
    public List<DepartmentListVo> querySurveyRuleDepartmentList(@RequestBody DepartmentListQo request) throws ControllerException {

        //医生所在团队，所具备满意度规则的科室列表
        List<DepartmentListVo> departmentListVos = new ArrayList<>();
        Map<String, DepartmentListVo> departmentListVoMap = new HashMap<>();
        DepartmentListVo departmentListVo;

        //已知用户医生编号 查询有权限的团队路径
        GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
        groupMemberRequest.setDocId(request.getDocId());
        groupMemberRequest.setTeamType(FollowTypeEnum.FUS_SATISFACTION.getType());
        List<Long> teamIdList = docTeamRpcService.queryTeamIdList(groupMemberRequest);
        List<DocTeamFusAuthority> docTeamFusAuthorities = docTeamFusAuthorityDAO.queryByDocId(request.getDocId(), teamIdList);
        if (CommonUtils.isNotEmpty(docTeamFusAuthorities)) {
            for (DocTeamFusAuthority docTeamFusAuthority : docTeamFusAuthorities) {
                departmentListVo = new DepartmentListVo();
                departmentListVo.setDepartmentId(docTeamFusAuthority.getDepartmentId());
                departmentListVo.setDepartmentName(docTeamFusAuthority.getDepartmentName());
                //添加机构过滤判断
                if (CommonUtils.isNotEmpty(request.getOrganizationId())) {
                    if (request.getOrganizationId().equals(docTeamFusAuthority.getOrganizationId())) {
                        departmentListVoMap.put(docTeamFusAuthority.getOrganizationId() + "^" + departmentListVo.getDepartmentId(), departmentListVo);
                    }
                } else {
                    departmentListVoMap.put(docTeamFusAuthority.getOrganizationId() + "^" + departmentListVo.getDepartmentId(), departmentListVo);
                }

            }
        }

        if (CommonUtils.isNotEmpty(departmentListVoMap.keySet())) {
            for (DepartmentListVo listVo : departmentListVoMap.values()) {
                departmentListVos.add(listVo);
            }
        }
        return departmentListVos;
    }


    /**
     * @description: 查询医生所在团队，所具备满意度规则的机构列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/9/24 12:44
     * @param: request
     * @return: org.atag.core.base.BaseResponse<java.util.List < clinical.bean.vo.OrganizationVo>>
     */
    @RpcService
    public List<OrganizationVo> querySurveyRuleOrganizationList(@RequestBody DepartmentListQo request) throws ControllerException {

        //医生所在团队，所具备满意度规则的机构列表
        List<OrganizationVo> organizationVoList = new ArrayList<>();
        Map<String, OrganizationVo> organizationVoMap = new HashMap<>();
        OrganizationVo organizationVo;

        //已知用户医生编号 查询有权限的团队路径
        GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
        groupMemberRequest.setDocId(request.getDocId());
        groupMemberRequest.setTeamType(FollowTypeEnum.FUS_SATISFACTION.getType());
        List<Long> teamIdList = docTeamRpcService.queryTeamIdList(groupMemberRequest);
        List<DocTeamFusAuthority> docTeamFusAuthorities = docTeamFusAuthorityDAO.queryByDocId(request.getDocId(), teamIdList);
        if (CommonUtils.isNotEmpty(docTeamFusAuthorities)) {
            for (DocTeamFusAuthority docTeamFusAuthority : docTeamFusAuthorities) {
                organizationVo = new OrganizationVo();
                organizationVo.setOrganizationId(docTeamFusAuthority.getOrganizationId());
                organizationVo.setOrganizationName(docTeamFusAuthority.getOrganizationName());
                organizationVoMap.put(docTeamFusAuthority.getOrganizationId(), organizationVo);
            }
        }

        if (CommonUtils.isNotEmpty(organizationVoMap.keySet())) {
            for (OrganizationVo listVo : organizationVoMap.values()) {
                organizationVoList.add(listVo);
            }
        }
        return organizationVoList;
    }

    private String queryUserId(String cardType, String cardId) {
        Certificate certificate = null;
        String userId = null;
        try {
            if (CommonUtils.isNotEmpty(cardType) && CommonUtils.isNotEmpty(cardId)) {
                certificate = new Certificate(IdentityTransformUtil.huLianIdentityToHcn(cardType), cardId, "01");
                if (hcn.util.CommonUtils.isNotNull(certificate)) {
                    Unique unique = mpiProvider.getUnique(certificate, hcn.common.Constants.USERID_SOURCE, hcn.common.Constants.USERID_TYPE_CODE);
                    if (null != unique) {
                        userId = SM4Utils.decryptData_ECB(unique.getUniqueId());
                    }
                }
            }
        } catch (MPIException e) {
            log.error("queryUserId出错:" + e.getMessage());
            e.printStackTrace();
        }
        return userId;
    }

    public AccessToken findUserTokenByUserId(String userId) {
        List<UserRoleToken> rs = null;
        AccessToken accessToken = null;
        try {
            User user = AccountCenter.getUser(userId);
            if (CommonUtils.isNotEmpty(user)) {
                Collection<UserRoleToken> tokens = user.getUserRoleTokens();
                rs = new ArrayList();
                Iterator var4 = tokens.iterator();

                while (var4.hasNext()) {
                    UserRoleToken ur = (UserRoleToken) var4.next();
                    rs.add(ur);
                }
                if (CommonUtils.isNotEmpty(rs)) {
                    accessToken = AppContextHolder.get().getBean(AccessTokenLoader.class).getByUser(rs.get(0).getUserId(), rs.get(0).getId(), rs.get(0).getDeptId());
                }
            }
        } catch (ControllerException e) {
            e.printStackTrace();
        }

        return accessToken;
    }


}
